﻿import { useEffect, useMemo } from 'react'
import { NavLink, Outlet, useLocation, useNavigate } from 'react-router-dom'
import { HeartIcon } from '@heroicons/react/24/solid'

import { NAV_ITEMS } from '../app/navigation'
import useCurrentUser from '../app/hooks/useCurrentUser'
import ThemeToggle from '../components/ThemeToggle'
import useThemeStore from '../app/store/themeStore'

const MOBILE_NAV_PATHS = ['/dashboard', '/assistant', '/profile']

const AppShell = () => {
  const location = useLocation()
  const navigate = useNavigate()
  const { data: user } = useCurrentUser()
  const theme = useThemeStore((s) => s.mode)
  const showTexture = useThemeStore((s) => s.showTexture)
  const glowLevel = useThemeStore((s) => s.glowLevel)
  const palette = useThemeStore((s) => s.palette)

  useEffect(() => {
    const root = document.documentElement
    // Texture
    root.style.setProperty('--grid-alpha', showTexture ? '0.04' : '0')
    // Glow
    const glowMap: Record<'low'|'medium'|'high', string> = { low: '0.35', medium: '0.55', high: '0.8' }
    root.style.setProperty('--glow-alpha', glowMap[glowLevel] || '0.55')
    // Palette accents as r,g,b
    root.style.setProperty('--accent-1', palette[0])
    root.style.setProperty('--accent-2', palette[1])
    root.style.setProperty('--accent-3', palette[2])
    root.style.setProperty('--accent-4', palette[3])
  }, [showTexture, glowLevel, palette])
  const activeItem = useMemo(() => {
    // pick the longest path that is a prefix of current pathname
    const pathname = location.pathname === '/' ? '/dashboard' : location.pathname
    let best = undefined as (typeof NAV_ITEMS)[number] | undefined
    for (const item of NAV_ITEMS) {
      const p = item.path
      if (pathname === p || pathname.startsWith(p + '/') || pathname.startsWith(p)) {
        if (!best || p.length > best.path.length) best = item
      }
    }
    return best
  }, [location.pathname])

  // 若未绑定情侣关系，除 /relationships 外均重定向到情侣配对页
  useEffect(() => {
    const noRelation = !user?.active_relationship_id
    const allowedPaths = ['/relationships', '/profile']
    const isAllowed = allowedPaths.some((path) => location.pathname.startsWith(path))
    if (noRelation && !isAllowed) {
      navigate('/relationships', { replace: true })
    }
  }, [user?.active_relationship_id, location.pathname, navigate])

  return (
    <div
      className={
        theme === 'vibrant'
          ? 'relative min-h-screen px-3 pb-16 pt-3 text-slate-900 sm:px-6 lg:pb-12 vibrant-theme'
          : 'relative min-h-screen px-3 pb-16 pt-3 text-slate-900 sm:px-6 lg:pb-12 soft-theme'
      }
    >
      {/* ambient aurora background for richer color ambiance */}
      <div className="aurora-bg" />
      <div className="mx-auto flex min-h-[calc(100vh-3rem)] w-full max-w-6xl flex-col gap-6 lg:flex-row">
        <DesktopSidebar activePath={activeItem?.path} />
        <main className="flex-1 overflow-y-auto lg:overflow-visible">
          <section className="flex-1">
            <div className="space-y-6 pb-12 page-transition">
              <Outlet />
            </div>
          </section>
        </main>
      </div>
      <MobileBottomNav />
    </div>
  )
}

type SidebarProps = {
  activePath?: string
}

const DesktopSidebar = ({ activePath }: SidebarProps) => {
  return (
    <aside className="sticky top-4 hidden w-full max-w-xs flex-col gap-4 self-start lg:flex">
      <div className="surface-card flex flex-col gap-4 p-6">
        <div>
          <span className="inline-flex items-center gap-2 rounded-full border border-[color:var(--border-soft)] bg-white px-3 py-1 text-xs font-semibold text-slate-500 shadow-inner">
            <HeartIcon className="h-4 w-4 text-blush-500" />
            Love Notes
          </span>
          <h2 className="mt-4 bg-gradient-to-r from-blush-500 via-lavender-500 to-sky-500 bg-clip-text font-display text-3xl font-semibold text-transparent">
            爱的日常，尽收眼底
          </h2>
          <p className="mt-3 text-sm leading-relaxed text-slate-500">
            日记、纪念日、生理期预测与智能助手，帮助你们沉淀回忆、创造仪式感。
          </p>
        </div>
      </div>
      <nav className="surface-card flex max-h-[70vh] flex-col gap-1 overflow-y-auto p-2">
        {NAV_ITEMS.map((item) => {
          const active = activePath === item.path
          return (
            <NavLink
              key={item.path}
              to={item.path}
              className={`group relative flex items-center gap-3 rounded-2xl px-4 py-3 text-sm font-medium transition-transform duration-200 ${
                active
                  ? 'bg-gradient-to-r from-blush-500 to-lavender-500 text-white shadow-card'
                  : 'text-slate-600 hover:bg-slate-100 hover:-translate-y-0.5 active:translate-y-0'
              }`}
            >
              <item.icon className={`h-5 w-5 ${active ? 'text-white' : 'text-blush-400 group-hover:text-blush-500'}`} />
              <div className="flex flex-col">
                <span>{item.label}</span>
                {item.description ? (
                  <span className={`text-xs ${active ? 'text-white/80' : 'text-slate-400'}`}>
                    {item.description}
                  </span>
                ) : null}
              </div>
              {active ? (
                <span className="pointer-events-none absolute inset-0 -z-10 rounded-2xl ring-1 ring-white/20" />
              ) : null}
            </NavLink>
          )
        })}
      </nav>
    </aside>
  )
}

const MobileBottomNav = () => {
  return (
    <nav className="pointer-events-none fixed inset-x-0 bottom-4 z-50 flex justify-center lg:hidden">
      <div className="glass-panel pointer-events-auto flex w-[90%] max-w-md items-center justify-between rounded-2xl border border-white/30 bg-white/90 px-6 py-3 shadow-card">
        {NAV_ITEMS.filter((item) => MOBILE_NAV_PATHS.includes(item.path)).map((item) => (
          <NavLink
            key={item.path}
            to={item.path}
            end={item.path === '/assistant'}
            className={({ isActive }) =>
              `group flex flex-1 flex-col items-center gap-1 text-xs font-medium ${
                isActive ? 'text-blush-500' : 'text-slate-400 hover:text-slate-600'
              }`
            }
          >
            <item.icon className="h-5 w-5 transition-transform duration-200 group-hover:-translate-y-0.5" />
            {item.label}
            
          </NavLink>
        ))}
      </div>
    </nav>
  )
}

export default AppShell
